package xFGE.Timer
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.*;

	[Event(name="XTIMER_DEATH",type="xTimerEvent")]
	
	public class xTimer extends Sprite
	{
		//计时器存活
		public static const TIMER_STATE_ALIVE:String = "alive";
		//计时器死亡
		public static const TIMER_STATE_DEATH:String = "death";
		//计时器暂停
		public static const TIMER_STATE_PAUSE:String = "pause";
		//无限次计时
		public static const TIMER_TIMES_UNLIMITED :int = -1;
		
		/** 实例 */
		private static var _myInstance:xTimer;
		/** 计时器列表*/
		private var _timerArray:Array;
		

		public function xTimer()
		{
			//TODO: implement function
			if(_myInstance){
				throw new Error("请用getInstance获取实例");
			}
			_timerArray = new Array();
			addEventListener(Event.ENTER_FRAME,_onEnterFrame);
			
		}
		
		/**
		 * 获取是列 
		 * @return 
		 * 
		 */
		public static function getInstance():xTimer
		{
			if(_myInstance == null) _myInstance = new xTimer();
			return _myInstance;
		}
		/**
		 * 增加计时器 
		 * @param key 计时器ID
		 * @param interval 计时器间隔
		 * @param callback 计时器回调
		 * @param times 响应次数
		 * 
		 */
		public function AddTimer(key:String,interval:int,callback:Function,times:int = TIMER_TIMES_UNLIMITED):void
		{
			//_timerArray[Timer.TimerKey] = Timer;
			var timer:xTimerObj = new xTimerObj(key,interval,callback,times);
			timer.addEventListener(xTimerEvent.XTIMER_DEATH,_onTimerDeath);
			_timerArray.push(timer);
		}
		
		/**
		 * 移除计时器 
		 * @param key 计时器key
		 * 
		 */
		public function RemoveTimer(timer:xTimerObj):void{
			var index:int = _timerArray.indexOf(timer);
			if(index >=0){
				_timerArray.splice(index,1);
				timer.removeEventListener(xTimerEvent.XTIMER_DEATH,_onTimerDeath);
			}
		}
		
		/**
		 * 获取计时器 
		 * @param key 计时器key
		 * @return 
		 * 
		 */
		public function GetTimer(key:String):xTimerObj
		{
			for each (var timer:xTimerObj in _timerArray){
				if(timer.TimerKey == key) return timer;
			}
			return null;
		}
		
		/**
		 * 每帧回调 
		 * @param eveObj 
		 * 
		 */
		private function _onEnterFrame(eveObj:Event):void
		{
			if(_timerArray.length == 0) return;
			var gobalTime:int = getTimer();
			for each(var key:xTimerObj in _timerArray){
				key.Update(gobalTime);
			}
		}
		
		private function _onTimerDeath(eveObj:Event):void
		{
			var timerDeath:xTimerEvent = new xTimerEvent(xTimerEvent.XTIMER_DEATH);
			timerDeath.timer = eveObj.target as xTimerObj;
			dispatchEvent(timerDeath);
			return;
		}
	}
}